package com.medata.conf;

import com.medata.dataObject.Actiondef;
import com.medata.dataObject.HotWords;
import com.medata.exeptions.YunExceptions;
import com.medata.service.*;
import com.medata.utils.PreUtils;
import org.apache.commons.io.FileUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import java.io.File;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ：zb
 * @date ：Created in 2019/5/21 0021 16:18
 * @description：
 */
@Component
public class ScheduledConf {
    @Value("${FilePath}")
    private String filePath;
    @Autowired
    private ActiondefService actiondefService;
    @Autowired
    private LogdetailService logdetailService;
    @Autowired
    private LogSearchService logSearchService;
    @Autowired
    private LogloginService logloginService;
    @Autowired
    private LogMakeDocumentService logMakeDocumentService;
    @Autowired
    private LogdispprjService logdispprjService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HotWordsService hotWordsService;
    @Autowired
    private CategoryService categoryService;
    @Value("${solrPath}")
    private String solrPath;
    @Autowired
    private EntityManager entityManager;

    //删除缓存
    @Scheduled(cron = "0 0 23 * * ?")
    public void deleteTemp() {
        String path = filePath + "/tempFiles";
        File file = new File(path);
        if (file.exists()) {
            try {
                FileUtils.deleteDirectory(file);
            } catch (Exception e) {
                throw new YunExceptions(0, "日常删除文件时出错");
            }
        }
    }

    //自动删除日志
    @Scheduled(cron = "00 00 23 * * ?")
    public void deleteLogs() {
        List<Actiondef> all = actiondefService.findAll();
        for (Actiondef actiondef : all) {
            Timestamp lastdeletetime = actiondef.getLastdeletetime();
            String lastTime = lastdeletetime.toString();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDateTime now = LocalDateTime.now(ZoneOffset.of("+8"));
            String NowTime = now.format(formatter);
            lastTime = lastTime.substring(0, 10);
            lastTime = lastTime.replaceAll("-", "");
            String newTime = NowTime.replaceAll("-", "");
            int i = Integer.valueOf(newTime) - Integer.valueOf(lastTime);
            if (i >= (Integer.valueOf(actiondef.getRoundday()))) {
                if (actiondef.getActionid().equals("100") | actiondef.getActionid().equals("101") | actiondef.getActionid().equals("102") | actiondef.getActionid().equals("103")) {
                    logMakeDocumentService.deleteByLogtimeBetweenAndActionid(lastdeletetime, Timestamp.valueOf(NowTime + " 00:00:00"), Integer.valueOf(actiondef.getActionid()));
                } else if (actiondef.getActionid().equals("200") | actiondef.getActionid().equals("201")) {
                    logloginService.deleteByLogtimeBetweenAndActionid(lastdeletetime, Timestamp.valueOf(NowTime + " 00:00:00"), Integer.valueOf(actiondef.getActionid()));
                } else if (actiondef.getActionid().equals("300") | actiondef.getActionid().equals("301")) {
                    logSearchService.deleteByLogTimeBetweenAndActionId(lastdeletetime, Timestamp.valueOf(NowTime + " 00:00:00"), Integer.valueOf(actiondef.getActionid()));
                } else if (actiondef.getActionid().equals("400")) {
                    logdetailService.deleteByLogtimeBetween(lastdeletetime, Timestamp.valueOf(NowTime + " 00:00:00"));
                } else if (actiondef.getActionid().equals("500")) {
                    logdispprjService.deleteByLogtimeBetweenAndActionid(lastdeletetime, Timestamp.valueOf(NowTime + " 00:00:00"), actiondef.getActionid());
                }
                actiondef.setLastdeletetime(Timestamp.valueOf(NowTime + " 00:00:00"));
                actiondefService.saveOrUpdate(actiondef);
            }
        }
    }

    //每隔30分组更新最热词汇
    @Scheduled(cron = "* */30 * * * ?")
    public void updateHotWords() {
        List<HotWords> hotWords = hotWordsService.topHotFind();
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        List<String> words = new ArrayList<>();
        for (HotWords hot : hotWords) {
            words.add(hot.getHotWord());
        }
        ops.set("hotWords", words.toString(), 6000, TimeUnit.MINUTES);
    }

    //每隔30分组更新最新词汇
    @Scheduled(cron = "* */30 * * * ?")
    public void updateNewWords() {
        HttpSolrServer solrServer = new HttpSolrServer(solrPath + "words");
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setStart(0);
        query.setRows(10);
        query.setSort("CreateDate", SolrQuery.ORDER.desc);
        query.set("fl", "word");
        List<String> list = new ArrayList<>();
        try {
            QueryResponse response = solrServer.query(query);
            SolrDocumentList results = response.getResults();
            if (results != null && !results.isEmpty()) {
                for (SolrDocument document : results) {
                    String word = (String) document.get("word");
                    if (word != null && !word.isEmpty()) {
                        list.add(word);
                    }
                }
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                ops.set("newWords", list.toString(), 6000, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new YunExceptions(0, "自动更新最新词汇出现bug");
        }

    }

    //每天晚上8点将首字母对应的文字及读音放在redis
    @Scheduled(cron = "00 00 20 * * ?")
    public void pronunciations() {
        PreUtils.prePronunciations(redisTemplate,solrPath);
    }

    //每天23点更新excel文件
    @Scheduled(cron = "00 30 23 * * ?")
    public void preExcel(){
//        ExcelUtils.preExcels();
    }

}
